<template>
  <div class="log-source">
    <h1 class="page-title">日志采集配置</h1>
    
    <div class="card">
      <div class="toolbar">
        <el-button type="primary" @click="openDialog(null)">
          <el-icon><Plus /></el-icon> 新建采集源
        </el-button>
      </div>
      
      <el-table :data="sourceList" stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="sourceType" label="类型" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.sourceType === 'file' ? '文件' : '网络' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sourceName" label="名称" width="200" />
        <el-table-column prop="config" label="配置" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastHeartbeat" label="最后心跳" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openDialog(scope.row)">编辑</el-button>
            <el-button type="info" size="small" @click="viewMonitor(scope.row)">监控</el-button>
            <el-button type="danger" size="small" @click="deleteSource(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空状态 -->
      <el-empty
        v-if="!loading && sourceList.length === 0"
        description="暂无采集源，点击上方按钮创建"
      />
    </div>
    
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑采集源' : '新建采集源'"
      width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="form.sourceType">
            <el-radio label="file">文件</el-radio>
            <el-radio label="network">网络</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配置">
          <el-input v-model="form.config" type="textarea" :rows="5" placeholder="JSON配置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" :disabled="submitLoading">取消</el-button>
        <el-button type="primary" @click="submit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 监控详情对话框 -->
    <el-dialog
      v-model="monitorDialogVisible"
      title="采集源监控详情"
      width="700px"
    >
      <div v-if="currentMonitor" v-loading="monitorLoading">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="采集源ID">
            {{ currentMonitor.sourceId }}
          </el-descriptions-item>
          <el-descriptions-item label="采集源名称">
            {{ currentSourceName }}
          </el-descriptions-item>
          <el-descriptions-item label="成功采集">
            <el-tag type="success" size="large">
              {{ currentMonitor.successCount || 0 }} 条
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="失败采集">
            <el-tag type="danger" size="large">
              {{ currentMonitor.failCount || 0 }} 条
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="成功率" :span="2">
            <el-progress
              :percentage="calculateSuccessRate(currentMonitor)"
              :color="getProgressColor(calculateSuccessRate(currentMonitor))"
              :stroke-width="20"
            />
          </el-descriptions-item>
          <el-descriptions-item label="最后采集时间" :span="2">
            {{ currentMonitor.lastCollectTime || '暂无数据' }}
          </el-descriptions-item>
          <el-descriptions-item label="最后心跳时间" :span="2">
            {{ currentMonitor.lastHeartbeat || '暂无数据' }}
          </el-descriptions-item>
          <el-descriptions-item label="错误信息" :span="2">
            <el-alert
              v-if="currentMonitor.errorMsg"
              :title="currentMonitor.errorMsg"
              type="error"
              :closable="false"
            />
            <span v-else style="color: #67c23a">✅ 运行正常</span>
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 20px">
          <el-statistic-card>
            <template #title>
              <span style="font-size: 16px; font-weight: bold">📊 采集统计</span>
            </template>
            <el-row :gutter="16" style="margin-top: 10px">
              <el-col :span="12">
                <el-statistic
                  title="总采集数"
                  :value="(currentMonitor.successCount || 0) + (currentMonitor.failCount || 0)"
                >
                  <template #prefix>
                    <el-icon color="#409eff"><Document /></el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="12">
                <el-statistic
                  title="成功率"
                  :value="calculateSuccessRate(currentMonitor)"
                  suffix="%"
                >
                  <template #prefix>
                    <el-icon color="#67c23a"><CircleCheck /></el-icon>
                  </template>
                </el-statistic>
              </el-col>
            </el-row>
          </el-statistic-card>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="monitorDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, CircleCheck } from '@element-plus/icons-vue'
import * as logSourceApi from '@/api/logSource'

const sourceList = ref([])
const dialogVisible = ref(false)
const loading = ref(false)
const submitLoading = ref(false)

// 监控相关
const monitorDialogVisible = ref(false)
const monitorLoading = ref(false)
const currentMonitor = ref(null)
const currentSourceName = ref('')

const form = reactive({
  id: null,
  name: '',
  sourceType: 'file',
  config: ''
})

// 加载采集源列表
const loadSources = async () => {
  loading.value = true
  try {
    const res = await logSourceApi.getLogSourceList()
    if (res.code === 200) {
      sourceList.value = res.data || []
    } else {
      ElMessage.warning(res.message || '加载失败')
    }
  } catch (error) {
    console.error('加载采集源列表失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 打开对话框
const openDialog = (source) => {
  if (source) {
    Object.assign(form, source)
  } else {
    form.id = null
    form.name = ''
    form.sourceType = 'file'
    form.config = ''
  }
  dialogVisible.value = true
}

// 提交保存
const submit = async () => {
  if (!form.name) {
    ElMessage.warning('请输入名称')
    return
  }
  if (!form.config) {
    ElMessage.warning('请输入配置')
    return
  }
  
  // 验证配置是否为有效JSON
  try {
    JSON.parse(form.config)
  } catch (error) {
    ElMessage.error('配置必须是有效的JSON格式')
    return
  }
  
  submitLoading.value = true
  try {
    let res
    if (form.id) {
      // 更新
      res = await logSourceApi.updateLogSource(form)
    } else {
      // 创建
      res = await logSourceApi.createLogSource(form)
    }
    
    if (res.code === 200) {
      ElMessage.success(form.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadSources()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 删除采集源
const deleteSource = async (source) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除采集源 "${source.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await logSourceApi.deleteLogSource(source.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadSources()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 查看监控
const viewMonitor = async (source) => {
  currentSourceName.value = source.sourceName ||source.name || `采集源 #${source.id}`
  console.log('查看监控:', source.sourceName)
  monitorDialogVisible.value = true
  monitorLoading.value = true
  
  try {
    const res = await logSourceApi.getSourceMonitor(source.id)
    if (res.code === 200) {
      currentMonitor.value = res.data
    } else {
      ElMessage.error(res.message || '获取监控数据失败')
    }
  } catch (error) {
    console.error('获取监控数据失败:', error)
    ElMessage.error('获取监控数据失败')
  } finally {
    monitorLoading.value = false
  }
}

// 计算成功率
const calculateSuccessRate = (monitor) => {
  if (!monitor) return 0
  const total = (monitor.successCount || 0) + (monitor.failCount || 0)
  if (total === 0) return 0
  return Math.round((monitor.successCount || 0) / total * 100)
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage >= 90) return '#67c23a'
  if (percentage >= 70) return '#e6a23c'
  return '#f56c6c'
}

onMounted(() => {
  loadSources()
})
</script>

<style scoped lang="scss">
.log-source {
  .toolbar {
    margin-bottom: 20px;
  }
}
</style>

